import router from "@/router/index.js";
import store from "@/store/index.js";
import user from "@/store/modules/userStore.js";
import Nprogress from 'nprogress'
import {getToken, handleRouter} from "@/utils";
import asyncRoutes from "@/router/asyncRoutes";

// 白名单路由
const whiteList = ['/login']
const userStore = user(store)

// 添加动态路由（优化版）
const addDynamicRoutes = () => {
    const userMenu = handleRouter(userStore.menuData);
    // 过滤掉返回菜单中不存在的
    const filterMenu = asyncRoutes.filter((menu) => {
        return userMenu.includes(menu.path)
    })
    filterMenu.forEach(route => {
        router.addRoute('HomePage', route);
    });
};

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
    Nprogress.start();
    const tokenData = getToken();
    const token = tokenData?.token; // 使用可选链操作符
    if (token) {
        if (to.path === '/login') {
            next({path: '/', replace: true});
            return;
        }
        try {
            const userData = userStore.userData;
            if (!userData || Object.keys(userData).length === 0) {
                await userStore.getUserInfo();
                addDynamicRoutes();
                next({path: to.path, replace: true});
                // next()
            } else {
                next()
            }
        } catch (error) {
            next(`/login?redirect=${to.path}`);
        }
    } else {
        if (whiteList.includes(to.path)) {
            next();
        } else {
            next(`/login?redirect=${to.path}`);
        }
    }
    if (to.meta.title) {
        document.title = `${to.meta.title}`;
    }
});

// 路由后置守卫
router.afterEach((to) => {
    Nprogress.done();
});
